package edu.ynu.hhy.architectureclass.dao.daoImpl;

import edu.ynu.hhy.architectureclass.dao.SensorDataDao;
import edu.ynu.hhy.architectureclass.entity.SensorData;
import edu.ynu.hhy.architectureclass.entity.SensorDataRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public abstract class SensorDataDaoImpl implements SensorDataDao {

    @Value("${fbox.api.sensor.url}") // 传感器 API 的 URL
    private String fboxSensorUrl;

    @Value("${fbox.access.token}") // FBox API 的访问令牌
    private String accessToken;

    private final RestTemplate restTemplate = new RestTemplate();

    @Override
    public List<SensorData> findByDeviceSerial(String deviceSerial) {
        String boxNo = "300023040071"; // 固定的 boxNo
        String url = fboxSensorUrl + "?boxNo=" + boxNo;

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + accessToken); // 带上 accessToken
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 创建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("ids", List.of(deviceSerial)); // 使用设备的序列号作为传感器 ID

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        // 发送请求
        try {
            ResponseEntity<List> response = restTemplate.exchange(url, HttpMethod.POST, entity, List.class);
            return response.getBody();
        } catch (Exception e) {
            System.err.println("API 调用异常: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}